﻿#include "widget.h"
#include "ui_widget.h"
#include <QtDebug>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget),
    hLayoutXCenter(new QHBoxLayout),
    hLayoutYCenter(new QHBoxLayout),
    hLayoutXOffset(new QHBoxLayout),
    hLayoutYOffset(new QHBoxLayout),
    hLayoutZoom(new QHBoxLayout),
    vLayoutParam(new QVBoxLayout),
    hLayoutMain(new QHBoxLayout),
    XOffset(20404000),
    YOffset(3918000),
    ZoomDelta(0.1),
    XCenter(1500),
    YCenter(800),
    dxf(new DL_Dxf)
{
    ui->setupUi(this);
    Scene = new QGraphicsScene;
#if 0
    QGraphicsLineItem* Line = new QGraphicsLineItem;
    Scene->setSceneRect(QRectF(0, 0, 790, 490));
    Line->setX(50);
    Line->setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);
    Line->setLine(QLineF(QPointF(0, Scene->height() - 0), QPointF(50, Scene->height() - 50)));
    Scene->addItem(Line);
    QGraphicsTextItem* Text = new QGraphicsTextItem;
    Text->setX(100);
    Text->setY(100);
    Text->setPlainText("李江军，Age:26");
    Text->setZValue(20);
    //  设置透明度，值范围: 0-1
    Text->setOpacity(0.6);
    // 设置角度
    Text->setRotation(-50);
    // 设置可鼠标拖动、 可选中
    Text->setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);
    Scene->addItem(Text);
    QGraphicsEllipseItem* Ellipse = new QGraphicsEllipseItem;
    Ellipse->setRect(QRectF(150, Scene->height() - 150, 50, 50));
    Ellipse->setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);
    Scene->addItem(Ellipse);
#endif
    Scene->setBackgroundBrush(QBrush(QColor(0, 0, 0)));
    View = new InteractiveView(this);
    View->setInteractive(true);
    View->setDragMode(QGraphicsView::ScrollHandDrag);
    View->setScene(Scene);
    View->setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);
//    View->setGeometry(0, 0, this->width(), this->height() - 50);
    View->show();
    vLayoutParam->addWidget(ui->BtnReadDXF);
    hLayoutXCenter->addWidget(ui->label_4);
    hLayoutXCenter->addWidget(ui->EditXCenter);
    vLayoutParam->addLayout(hLayoutXCenter);
    hLayoutYCenter->addWidget(ui->label_5);
    hLayoutYCenter->addWidget(ui->EditYCenter);
    vLayoutParam->addLayout(hLayoutYCenter);
    hLayoutXOffset->addWidget(ui->label);
    hLayoutXOffset->addWidget(ui->XOffset);
    vLayoutParam->addLayout(hLayoutXOffset);
    hLayoutYOffset->addWidget(ui->label_2);
    hLayoutYOffset->addWidget(ui->YOffset);
    vLayoutParam->addLayout(hLayoutYOffset);
    hLayoutZoom->addWidget(ui->label_3);
    hLayoutZoom->addWidget(ui->Zoom);
    vLayoutParam->addLayout(hLayoutZoom);
    vLayoutParam->addWidget(ui->pushButton);
    vLayoutParam->addWidget(ui->pushButton_2);
    vLayoutParam->addStretch();
    hLayoutMain->addWidget(View);
    hLayoutMain->addLayout(vLayoutParam);
    hLayoutMain->setContentsMargins(0, 0, 5, 0);
    hLayoutMain->setStretch(0, 90);
    hLayoutMain->setStretch(1, 10);
    this->setLayout(hLayoutMain);
    ui->EditXCenter->setText(QString::number(XCenter, 'f', 3));
    ui->EditYCenter->setText(QString::number(YCenter, 'f', 3));
    ui->XOffset->setText(QString::number(XOffset, 'f', 3));
    ui->YOffset->setText(QString::number(YOffset, 'f', 3));
    ui->Zoom->setText(QString::number(ZoomDelta, 'f', 3));

    // setting
//    View->setViewportUpdateMode(QGraphicsView::NoViewportUpdate);
}

Widget::~Widget()
{
    delete dxf;
    dxf = nullptr;
    QList<QGraphicsItem *> items = Scene->items();
    for (auto i = 0; i < items.size(); i++) {
        Scene->removeItem(items[i]);
        delete items[i];
    }
    hLayoutXCenter->deleteLater();
    hLayoutYCenter->deleteLater();
    hLayoutXOffset->deleteLater();
    hLayoutYOffset->deleteLater();
    hLayoutZoom->deleteLater();
    vLayoutParam->deleteLater();
    hLayoutMain->deleteLater();
    Scene->deleteLater();
    View->deleteLater();
    delete ui;
}

/**
 * Sample implementation of the method which handles layers.
 */
void Widget::addLayer(const DL_LayerData& data)
{
    qDebug("LAYER: %s flags: %d", data.name.c_str(), data.flags);
    printAttributes();
}

/**
 * Sample implementation of the method which handles point entities.
 */
void Widget::addPoint(const DL_PointData& data)
{
    qDebug("POINT    (%6.3f, %6.3f, %6.3f)",
           data.x, data.y, data.z);
    printAttributes();
}

/**
 * Sample implementation of the method which handles line entities.
 */
void Widget::addLine(const DL_LineData& data)
{
    if(!dxf->getStartEntities())
        return;
    QGraphicsLineItem* Line = new QGraphicsLineItem;
    QLineF p;
    p.setP1(Line->mapFromScene(QPointF(data.x1 - XOffset, YOffset - data.y1)));
    p.setP2(Line->mapFromScene(QPointF(data.x2 - XOffset, YOffset - data.y2)));
    Line->setLine(p);
    QPen pen;
    pen.setWidth(0);
    pen.setColor(QColor(255, 185, 15));
    Line->setPen(pen);
    Scene->addItem(Line);
    qDebug("LINE     (%6.3f, %6.3f, %6.3f) (%6.3f, %6.3f, %6.3f)",
           data.x1, data.y1, data.z1, data.x2, data.y2, data.z2);
    printAttributes();
    // 画图时可以防止页面假死，items 按顺序画出来
    QCoreApplication::processEvents();
}

/**
 * Sample implementation of the method which handles arc entities.
 */
void Widget::addArc(const DL_ArcData& data)
{
    qDebug("ARC      (%6.3f, %6.3f, %6.3f) %6.3f, %6.3f, %6.3f",
           data.cx, data.cy, data.cz,
           data.radius, data.angle1, data.angle2);
    printAttributes();
}

/**
 * Sample implementation of the method which handles circle entities.
 */
void Widget::addCircle(const DL_CircleData& data)
{
    if(!dxf->getStartEntities())
        return;
    QGraphicsEllipseItem* Ellipse = new QGraphicsEllipseItem;
    Ellipse->setRect(QRectF(data.cx - XOffset - data.radius, YOffset - data.cy - data.radius, data.radius * 2, data.radius * 2));
    QPen pen;
    pen.setWidth(0);
    pen.setColor(QColor(255, 185, 15));
    Ellipse->setPen(pen);
    Scene->addItem(Ellipse);
    qDebug("CIRCLE   (%6.3f, %6.3f, %6.3f) %6.3f",
           data.cx, data.cy, data.cz,
           data.radius);
    printAttributes();
}


/**
 * Sample implementation of the method which handles polyline entities.
 */
void Widget::addPolyline(const DL_PolylineData& data)
{
    qDebug("POLYLINE ");
    qDebug("flags: %d", static_cast<int>(data.flags));
    printAttributes();
}


/**
 * Sample implementation of the method which handles vertices.
 */
void Widget::addVertex(const DL_VertexData& data)
{
    qDebug("VERTEX   (%6.3f, %6.3f, %6.3f) %6.3f",
           data.x, data.y, data.z,
           data.bulge);
    printAttributes();
}


void Widget::add3dFace(const DL_3dFaceData& data)
{
    qDebug("3DFACE");
    for (int i=0; i<4; i++) {
        qDebug("   corner %d: %6.3f %6.3f %6.3f",
            i, data.x[i], data.y[i], data.z[i]);
    }
    printAttributes();
}

void Widget::addText(const DL_TextData& data)
{
    if(!dxf->getStartEntities())
        return;
    QString value = QString::fromStdString(data.text);
    double Angle = data.angle * 57.2958;
    value.replace("%%D", "°");
    qDebug() << QString("TEXT: X=%1, Y=%2, Text=%3, Angel=%4").
                arg(data.ipx).
                arg(data.ipy).
                arg(value).
                arg(Angle);
    QGraphicsTextItem* Text = new QGraphicsTextItem;
    Text->setX(data.ipx - XOffset);
    Text->setY(YOffset - data.ipy - 13);
    Text->setDefaultTextColor(QColor(Qt::white));
    Text->setPlainText(value);
    // 设置角度
    Text->setRotation(-Angle);
    Scene->addItem(Text);
    QCoreApplication::processEvents();
}

void Widget::printAttributes()
{
    qDebug("  Attributes: Layer: %s, ", attributes.getLayer().c_str());
    qDebug(" Color: ");
    if (attributes.getColor()==256)	{
        qDebug("BYLAYER");
    } else if (attributes.getColor()==0) {
        qDebug("BYBLOCK");
    } else {
        qDebug("%d", attributes.getColor());
    }
    qDebug(" Width: ");
    if (attributes.getWidth()==-1) {
        qDebug("BYLAYER");
    } else if (attributes.getWidth()==-2) {
        qDebug("BYBLOCK");
    } else if (attributes.getWidth()==-3) {
        qDebug("DEFAULT");
    } else {
        qDebug("%d", attributes.getWidth());
    }
    qDebug(" Type: %s", attributes.getLinetype().c_str());
}

void Widget::on_BtnReadDXF_clicked()
{
    std::string file = "F:/QuakeCollectLocate/Cad/zl_ansi.dxf";
//    DL_Dxf* dxf = new DL_Dxf();
    if (!dxf->in(file.c_str(), this)) { // if file open failed
        std::cerr << file << " could not be opened.\n";
        return;
    }
//    delete dxf;

}

void Widget::on_XOffset_editingFinished()
{
    XOffset = ui->XOffset->text().toDouble();
}

void Widget::on_YOffset_editingFinished()
{
    YOffset = ui->YOffset->text().toDouble();
}

void Widget::on_Zoom_editingFinished()
{
    ZoomDelta = ui->Zoom->text().toDouble();
    qreal factor = View->transform().scale(static_cast<qreal>(ZoomDelta), static_cast<qreal>(ZoomDelta)).mapRect(QRectF(0, 0, 1, 1)).width();
    if (factor < 0.07 || factor > 100)
        return;
    View->scale(ZoomDelta, ZoomDelta);
}

void Widget::on_EditXCenter_editingFinished()
{
    XCenter = ui->EditXCenter->text().toDouble();
    View->centerOn(XCenter, YCenter);
}

void Widget::on_EditYCenter_editingFinished()
{
    YCenter = ui->EditYCenter->text().toDouble();
    View->centerOn(XCenter, YCenter);
}

void Widget::on_pushButton_clicked()
{
    qreal x = 20404614;
    qreal y = 3918540;
    QGraphicsEllipseItem* Ellipse = new QGraphicsEllipseItem;
    Ellipse->setRect(x - XOffset, y - YOffset, 30, 30);
    Ellipse->setPen(QColor(Qt::white));
    Ellipse->setBrush(QBrush(QColor(Qt::red)));
    Ellipse->setFlags(QGraphicsItem::ItemIsSelectable);
    Scene->addItem(Ellipse);
    View->centerOn(x - XOffset, y - YOffset);
}

void Widget::on_pushButton_2_clicked()
{
#if 1
    qreal x = 20404614;
    qreal y = 3918540;
    // x - XOffset - 30, y - YOffset - 30, x - XOffset + 30, y - YOffset + 30
    QRectF Rect(x - XOffset, y - YOffset, 5 , 5);
    QList<QGraphicsItem *> itemList = Scene->items(Rect);
#else
    QList<QGraphicsItem *> itemList = Scene->selectedItems();
#endif
    for (auto i = 0; i < itemList.size(); i++) {
        Scene->removeItem(itemList[i]);
        delete itemList[i];
    }
    qDebug() << qVersion();
}
